<?php
/**
 *
 * PHP API 商品控制器
 * @author jeff liu
 * powered by jeff liu
 */
class GoodsApp extends ApiApp
{

    function __construct()
    {
        $this->GoodsApp();
    }

    function GoodsApp()
    {
        parent::__construct();
        $this->_goods_mod =& api_model('goods');
    }

    /**
     * 获得商品的销售记录
     * @id string required 商品id 多个
     * powered by jeff 2011-5-20
     */
    function apiGetGoodsSaleLog()
    {
        $goods_id = $_REQUEST['id'];
        if (isset($_REQUEST['begin_time'])) {
            $begin_time = $_REQUEST['begin_time'];
        }
        if (isset($_REQUEST['end_time'])) {
            $end_time = $_REQUEST['end_time'];
        }
        $goods_ids = array();
        if (empty($goods_id)) {
            ApiError::showError('goods_id_required', 1);
            return;
        }

        $order_goods_mod =& api_model('ordergoods');

        $goods_ids_arr = explode(',', $goods_id);
        foreach ((array)$goods_ids_arr as $tmp_id) {
            if (!empty($tmp_id)) {
                $goods_ids[] = $tmp_id;
            }
        }
        $conditions = sprintf(
            ' goods_id in (%s) AND status >="%s"',
            implode(',', $goods_ids),
            ORDER_ACCEPTED
        ); //销售记录为所有已付款状态之后的订单（包括已付款）

        if (!empty($begin_time) && !empty($end_time)) {
            $conditions = $conditions . " AND add_time >= {$begin_time} AND add_time <= {$end_time}";
        }

        $sales_list = $order_goods_mod->find(
            array(
                'conditions' => $conditions,
                'join' => 'belongs_to_order',
                'fields' => 'buyer_id, buyer_name, add_time,pay_time as operate_time, anonymous, goods_id, specification, price, quantity, evaluation, goods_name',
                'order' => 'add_time desc',
            )
        );
        $this->echo_result($sales_list);
        exit();
    }

    /**
     * 获得商品价格
     * @id float required 商品ID
     */
    function apiGetGoodsPrice()
    {
        $result = $this->_getGoodsFieldByGoodsId('price');
        echo $result;
        exit;
    }

    /**
     * 获得cool公司需要的数据
     * powered by yanshuai 2011-09-16
     */
    function apiGetCoolGoodsMsgByGoodsId()
    {
        $goods_ids = $this->_get_goods_ids();
        $goods_ids = implode(',', $goods_ids);
        $rs = $this->_getCoolGoodsMsgByGoodsId($goods_ids);
        $this->echo_result($rs);
        exit;
    }

    /**
     * 通话特定商品获得店铺销售排行并排序
     */
    function apiGetStoreSortByGoodSeledNum()
    {
        $rs = $this->_getStoreSortByGoodSeledNum();
        $this->echo_result($rs);
        exit();
    }

    /**
     * 获得车辆销售排行
     */
    function apiGetGoodsSortBySeledNum()
    {
        $rs = $this->_getGoodsSortBySeledNum();
        $this->echo_result($rs);
        exit();
    }

    /**
     * 获得商品总销售信息(包括销售额，及数量)
     * powered by yanshuai 2011-09-05
     */
    function apiGetGoodsSaledMsg()
    {
        $rs = $this->_getGoodsSaledMsg();
        $this->echo_result($rs);
        exit;
    }

    /**
     * 获得商品默认图片
     * @id float required 商品ID
     * powered by jeff 2011-5-26
     */
    function apiGetGoodsDefaultImg()
    {
        $result = $this->_getGoodsFieldByGoodsId('default_image');
        echo $result;
        exit;
    }

    /**
     * 通话特定商品获得店铺销售排行并排序（支持时间段的查询）
     * @author yanshuai
     * @param String $order_id 店铺id
     * @return Array 店铺id做主键，相关数据组成的数组做值(包含：销量，店铺名等)
     */
    private function _getStoreSortByGoodSeledNum()
    {
        $store_mod = & api_model("store");
        $order_mod = & api_model('order');
        $order_goods_mod = & api_model('ordergoods');
        $goods_mod = & api_model('goods');

        if (isset($_REQUEST['begin_time'])) {
            $begin_time = $_REQUEST['begin_time'];
        }
        if (isset($_REQUEST['end_time'])) {
            $end_time = $_REQUEST['end_time'];
        }
        $conditions = sprintf('%s.status >="%s" AND ', $order_mod->alias, ORDER_ACCEPTED); //销售记录为所有已付款状态之后的订单（包括已付款）
        //若有时间限制，则需要连接order表进行判断限制
        if (!empty($begin_time) && !empty($end_time)) {
            $conditions = $conditions . "order_alias.add_time >= {$begin_time} AND order_alias.add_time <= {$end_time} AND ";
        }
        if (empty($_REQUEST['store_id'])) {
            error_reporting();
        } else {
            $store_id = $_REQUEST['store_id'];
        }
        /**
         * @todo 提交时 需要删除
         */
        $store_id = '18,17,16,119,47,23,28,698,697,77,78,79,66,45,46,47,48,49,5,7,8,35,118,119';
        $store_id = '119';
        //$conditions .= sprintf(' %s.seller_id in (%s)',$order_mod->alias,$store_id);
        $conditions .= sprintf(' %s.store_id in (%s) and ', $this->_goods_mod->alias, $store_id);
        //需要检测type,需要连接goods
        $type = "";
        if (!empty($_REQUEST['type'])) {
            $type = $_REQUEST['type'];
        } else {
            $type = 'car';
        }
        $conditions .= sprintf(' %s.type="%s" and ', $this->_goods_mod->alias, $type);
        $conditions .= sprintf(' %s.goods_id=%s.goods_id and ', $this->_goods_mod->alias, $order_goods_mod->alias);
        $conditions .= sprintf(' %s.order_id=%s.order_id ', $order_mod->alias, $order_goods_mod->alias);
        $rs = "";
        $rs = $order_goods_mod->find(
            array(
                'conditions' => $conditions,
                'join' => 'belongs_to_order,belongs_to_goods',
                'fields' => 'seller_id,order_goods.quantity,g.type,g.goods_id',
            )
        );
//dump($rs);
        $total_saled_num = 0;
        $goods_saled_msg = array();
        $goods_saled_msg[total_saled_num] = 0;
        $goods_saled_msg[total_saled_price] = 0;
        $store = array();
        foreach ($rs as $k => $v) {
            $goods_id = $v[goods_id];
            if (isset($store[$v[seller_id]])) {
                $store[$v[seller_id]][saled_num] = $store[$v[seller_id]][saled_num] + $v[quantity];
                $store[$v[seller_id]][goods_id][] = $v[goods_id];
            } else {
                $store[$v[seller_id]][saled_num] = $v[quantity];
            }
            unset($v[quantity]);
            unset($v[goods_id]);
            $store[$v[seller_id]] = array_merge($store[$v[seller_id]], $v);
        }
        //以下是取得店铺的名称，并合并到数据中
        $key = array_keys($store);
        $store_ids = implode(',', $key);
        $sql = sprintf('select store_id,store_name from chinapay_store where store_id in (%s)', $store_ids);
        $rs2 = $store_mod->getAll($sql);
        foreach ($rs2 as $k => $v) {
            if (isset($store[$v[store_id]])) {
                $store[$v[store_id]][store_name] = $v[store_name];
            } else {
                $store[$v[store_id]][store_name] = "无名";
            }
        }
        $store = array_msort($store, array('saled_num' => SORT_DESC)); //根据店铺的销售量进行排序
        dump($store);
    }

    /**
     * @author yanshuai
     * @param $store_id 店铺id
     * @return String
     */
    private function _getGoodsId_By_StoreId($store_id)
    {

    }

    /**
     * 获得车辆销售排行
     * @author yanshuai
     * @param $id 商品id
     * @return  Array goods_id做主键，相关数据组成的数组做值(包含：销量，店铺名等)
     * @todo 有待测试
     */
    private function _getGoodsSortBySeledNum()
    {
        $order_goods_mod = & api_model('ordergoods');

        if (isset($_REQUEST['begin_time'])) {
            $begin_time = $_REQUEST['begin_time'];
        }
        if (isset($_REQUEST['end_time'])) {
            $end_time = $_REQUEST['end_time'];
        }
        $conditions = sprintf('status >="%s" AND ', ORDER_ACCEPTED); //销售记录为所有已付款状态之后的订单（包括已付款）
        //若有时间限制，则需要连接order表进行判断限制
        if (!empty($begin_time) && !empty($end_time)) {
            $conditions = $conditions . "order_alias.add_time >= {$begin_time} AND order_alias.add_time <= {$end_time} AND ";
        }

        $rs = "";
        //查询通过goods_id
        $goods_ids = $this->_get_goods_ids();
        $goods_ids = implode(',', $goods_ids);
        $conditions = $conditions . sprintf(' %s.goods_id in (%s)', $order_goods_mod->alias, $goods_ids);

        $rs = $order_goods_mod->find(
            array(
                'conditions' => $conditions,
                'join' => 'belongs_to_order',
                'fields' => 'order_goods.goods_id,order_goods.quantity,order_goods.price',
            )
        );

        $total_saled_num = 0;
        $total_saled_price = 0;
        $goods_saled_msg = array();
        $goods_saled_msg[total_saled_num] = 0;
        $goods_saled_msg[total_saled_price] = 0;
        foreach ($rs as $k => $v) {
            if (isset($goods_saled_msg[$v[goods_id]])) {
                $goods_saled_msg[$v[goods_id]][saled_num] = $goods_saled_msg[$v[goods_id]][saled_num] + $v[quantity];
                $goods_saled_msg[$v[goods_id]][saled_price] = $goods_saled_msg[$v[goods_id]][saled_price] + $v[price] * $v[quantity];
            } else {
                $goods_saled_msg[$v[goods_id]][saled_num] = $v[quantity];
                $goods_saled_msg[$v[goods_id]][saled_price] = $v[price] * $v[quantity];
            }
            $goods_saled_msg[total_saled_num] = $goods_saled_msg[total_saled_num] + $v[quantity];
            $goods_saled_msg[total_saled_price] = $goods_saled_msg[total_saled_price] + $v[price] * $v[quantity];
            //echo $v[price]." * ".$v[quantity]." = ".$goods_saled_msg[total_saled_price];
            //echo "<br>";
        }
        //	dump($goods_saled_msg);
        return $goods_saled_msg;
    }

    /**
     * 获得商品总库存
     * powered by jeff 2011-6-2
     */
    function apiGetGoodsStock()
    {
        $result = $this->_getGoodsFieldByGoodsId('sum_stock');
        echo $result;
        exit;
    }

    /**
     * 获得商品的名称
     * powered by jeff 2011-05-24
     */
    function apiGetGoodsName()
    {
        $result = $this->_getGoodsFieldByGoodsId('goods_name');
        echo $result;
        exit;
    }

    /**
     * 获取商品已售出库存
     * powered by jeff 2011-6-2
     * TODO 需要完善
     */
    function apiGetGoodsSelledStock()
    {
        $result = $this->_getGoodsStock('SelledStock');
        echo $result;
    }

    /**
     * 获取商品等待付款库存
     * powered by jeff 2011-6-2
     */
    function apiGetGoodsWaitingPaiedStock()
    {
        $result = $this->_getGoodsStock('WaitingPaiedStock');
        echo $result;
    }

    /**
     * @id string 商品ID 多个id之间使用","
     */
    function apiGetGoodsStockByIds()
    {
        $goods_ids = $this->_get_goods_ids();
        //根据ID获得对应的结果
        $sql = sprintf(
            'SELECT goods_id, sum_stock
                           FROM %s  WHERE goods_id IN(%s)',
            $this->_goods_mod->table,
            implode(',', $goods_ids)
        );
        $goods_stock = $this->_goods_mod->getAll($sql);
        $this->echo_result($goods_stock);
    }

    /**
     *
     * powered by jeff 2011-6-3
     * @param unknown_type $type
     */
    private function _getGoodsStock($type = '')
    {
        $goods_id = $_REQUEST['goods_id'];
        if (empty($goods_id)) { //没有传goods_id 直接报错
            ApiError::showError('goods_id_required', 1);
            return;
        }

        $retrieve_goods_stock_mod =& api_model('retrieve_goods_stock');

        if ($type == 'WaitingPaiedStock') {
            $result = $retrieve_goods_stock_mod->getGoodsWaitingPaiedStock($goods_id);
        } else {
            if ($type == 'SelledStock') {
                $result = $retrieve_goods_stock_mod->getGoodsSelledStock($goods_id);
            }
        }

        $this->echo_result($result);
    }

    /**
     * 根据goods_id 获得单个商品字段值
     * powered by jeff 2011-5-31
     * @param string $field 字段名称(不需要添加表前缀)
     */
    private function _getGoodsFieldByGoodsId($field = '')
    {
        $goods_id = $_REQUEST['id'];

        if (empty($goods_id)) { //没有传goods_id 直接报错
            $error = ApiError::showError('goods_id_required', 1);
            echo $error;
            return;
        }
        //根据ID获得对应的结果
        $sql = sprintf(
            'SELECT %s.%s FROM %s %s WHERE %s.goods_id=%0.f',
            $this->_goods_mod->alias,
            $field,
            $this->_goods_mod->table,
            $this->_goods_mod->alias,
            $this->_goods_mod->alias,
            (float)$goods_id
        );

        $result = $this->_goods_mod->getOne($sql);
        $result = array('data' => $result);
        return $this->return_result($result);
    }

    /**
     * 获得商品详细信息
     * powered by jeff 2011-6-7
     * @todo 还没有完成
     */
    function apiGetGoodsDetail()
    {

    }

    /*
     *	根据商品获得补贴信息
     *	powered by wuwei 2011-08-18
     */
    function apiGetGoodsSubsidy()
    {
        $goods_info = array();
        $user_id = $_POST['user_id'];
        $phone_tel = $_POST['phone_tel'];
        $goods_urls = $_POST['goods_url'];
        foreach ($goods_urls as $goods_url) {
            if (!empty($goods_url) && $goods_url != '将商品地址粘贴在这里') {
                $goods_id = explode("&id=", $goods_url);
                $goods_info = array(
                    'user_id' => $user_id,
                    'goods_id' => $goods_id[1],
                    'phone_tel' => $phone_tel,
                );
                $subsidy_activities_model = & m('subsidy_activities');
                $subsidy_activities_model->add_subsidy($goods_info);
            }
        }
        $back_url = SITE_HUODONG_URL . "/index.php?app=activities&p=subsidy&act=action&mode=get_subsidy";
        header("Location:" . $back_url);
    }

    /**
     * 获取商品总销售信息(包括，销售量及销售额)<pre>
     * 可以通过goods_id(多个id用","分开)<br>也可以通过type来获得一类
     * 支持特定时间段的销售查询</pre>
     *
     * @author yanshuai
     * @return Array $goods_sale_msg
     *     <pre>goods_id为键相应的销售量与销售额组成的数组为值（eg:$goods_sale_msg[698][saled_num]）
     *         添加total_saled_num为键总销售为值
     *         添加total_saled_price为键总销饿为值
     * </pre>
     * @todo 有待进一步测试
     */
    private function _getGoodsSaledMsg()
    {
        $order_goods_mod = & api_model('ordergoods');

        if (isset($_REQUEST['begin_time'])) {
            $begin_time = $_REQUEST['begin_time'];
        }
        if (isset($_REQUEST['end_time'])) {
            $end_time = $_REQUEST['end_time'];
        }
        $conditions = sprintf('status >="%s" AND ', ORDER_ACCEPTED); //销售记录为所有已付款状态之后的订单（包括已付款）
        //若有时间限制，则需要连接order表进行判断限制
        if (!empty($begin_time) && !empty($end_time)) {
            $conditions = $conditions . "order_alias.add_time >= {$begin_time} AND order_alias.add_time <= {$end_time} AND ";
        }

        $rs = "";
        if (!isset($_REQUEST['type']) && isset($_REQUEST['id'])) {
            //查询通过goods_id
            $goods_ids = $this->_get_goods_ids();
            $goods_ids = implode(',', $goods_ids);
            $conditions = $conditions . sprintf(' %s.goods_id in (%s)', $order_goods_mod->alias, $goods_ids);

            $rs = $order_goods_mod->find(
                array(
                    'conditions' => $conditions,
                    'join' => 'belongs_to_order',
                    'fields' => 'order_goods.goods_id,order_goods.quantity,order_goods.price',
                )
            );

        } elseif (isset($_REQUEST['type']) && !isset($_REQUEST['id'])) {
            //查询店铺的指点店铺的汽车销售
            if (isset($_REQUEST['store_ids'])) {
                $conditions .= sprintf(
                    ' %s.store_id IN (%s) AND ',
                    $this->_goods_mod->alias,
                    trim($_REQUEST['store_ids'])
                );
            }
            //查询通过type,需要连接goods表查询goods_id
            $type = $_REQUEST['type'];
            $conditions .= sprintf(' %s.type="%s"', $this->_goods_mod->alias, $type);

            $rs = $order_goods_mod->find(
                array(
                    'conditions' => $conditions,
                    'join' => 'belongs_to_goods,belongs_to_order',
                    'fields' => 'order_goods.goods_id,order_goods.quantity,order_goods.price',
                )
            );
        }
        //下面组合数据，按指定的要求返回
        $total_saled_num = 0;
        $total_saled_price = 0;
        $goods_saled_msg = array();
        $goods_saled_msg['total_saled_num'] = 0;
        $goods_saled_msg['total_saled_price'] = 0;
        foreach ($rs as $k => $v) {
            if (isset($goods_saled_msg[$v['goods_id']])) {
                $goods_saled_msg[$v['goods_id']]['saled_num'] = $goods_saled_msg[$v['goods_id']]['saled_num'] + $v['quantity'];
                $goods_saled_msg[$v['goods_id']]['saled_price'] = $goods_saled_msg[$v['goods_id']]['saled_price'] + $v['price'] * $v['quantity'];
            } else {
                $goods_saled_msg[$v['goods_id']]['saled_num'] = $v['quantity'];
                $goods_saled_msg[$v['goods_id']]['saled_price'] = $v['price'] * $v['quantity'];
            }
            $goods_saled_msg['total_saled_num'] = $goods_saled_msg['total_saled_num'] + $v['quantity'];
            $goods_saled_msg['total_saled_price'] = $goods_saled_msg['total_saled_price'] + $v['price'] * $v['quantity'];
        }
        //	dump($goods_saled_msg);
        return $goods_saled_msg;
    }

    /**
     * powered by yanshuai 2011-09-18
     * @param $id 商品id(支持单个,多个查询)
     */
    private function _getCoolGoodsMsgByGoodsId($goods_ids)
    {
        //得到基本信息
        $conditions = sprintf('g.goods_id in(%s)', $goods_ids);
        $rs = $this->_goods_mod->find(
            array(
                'conditions' => $conditions,
                'join' => 'has_goodsstatistics',
                'fields' => 'g.goods_id,g.goods_name,g.price,g.original_price,views',
            )
        );
        //下面查询goods_id的销售记录
        $order_goods_mod = & api_model('ordergoods');
        $conditions = sprintf('status >="%s" AND ', ORDER_ACCEPTED); //销售记录为所有已付款状态之后的订单（包括已付款）
        $conditions = $conditions . sprintf(' %s.goods_id in (%s)', $order_goods_mod->alias, $goods_ids);
        $rs2 = $order_goods_mod->find(
            array(
                'conditions' => $conditions,
                'join' => 'belongs_to_order',
                'fields' => 'order_goods.goods_id,order_goods.quantity',
            )
        );
        $goods_saled_num = array();
        foreach ($rs2 as $k => $v) {
            if (isset($goods_saled_num[$v['goods_id']])) {
                $goods_saled_num[$v['goods_id']]['saled_num'] = $goods_saled_num[$v['goods_id']]['saled_num'] + $v['quantity'];
            } else {
                $goods_saled_num[$v['goods_id']]['saled_num'] = $v['quantity'];
            }
        }
        //下面把商品基本信息和销售量合并在一起,组合数据。返回
        $result_rs = array();
        foreach ($rs as $v) {
            $result_rs[$v['goods_id']] = $v;
            if (empty($goods_saled_num[$v['goods_id']])) {
                $result_rs[$v['goods_id']]['saled_num'] = 0;
            } else {
                $result_rs[$v['goods_id']]['saled_num'] = $goods_saled_num[$v['goods_id']]['saled_num'];
            }
        }
        return $result_rs;
        //return $this->return_result($result_rs);
    }

    function apiGetGoodsSaleLogByType()
    {
        if (!isset($_REQUEST['type'])) {
            return;
        }

        $order_goods_mod = & api_model('ordergoods');

        if (isset($_REQUEST['begin_time'])) {
            $begin_time = $_REQUEST['begin_time'];
        }
        if (isset($_REQUEST['end_time'])) {
            $end_time = $_REQUEST['end_time'];
        }
        $conditions = sprintf('status >="%s" AND ', ORDER_ACCEPTED); //销售记录为所有已付款状态之后的订单（包括已付款）
        //若有时间限制，则需要连接order表进行判断限制
        if (!empty($begin_time) && !empty($end_time)) {
            $conditions = $conditions . "order_alias.add_time >= {$begin_time} AND order_alias.add_time <= {$end_time} AND ";
        }


        //查询通过type,需要连接goods表查询goods_id
        $type = $_REQUEST['type'];
        $conditions .= sprintf(' %s.type="%s"', $this->_goods_mod->alias, $type);

        $rs = $order_goods_mod->find(
            array(
                'conditions' => $conditions,
                'join' => 'belongs_to_goods,belongs_to_order',
                'fields' => 'order.seller_id,order.pay_time,order_goods.goods_id,order_goods.quantity,order_goods.price',
                'order' => 'order.pay_time desc',
            )
        );


        $this->echo_result($rs);
    }

}